package com.ff.sca.product.controller;


import com.alipay.api.domain.Product;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ff.kvm.common.eunm.ProductTypeEnum;
import com.ff.sca.common.aoplog.ControllerLog;
import com.ff.sca.common.base.BaseController;
import com.ff.sca.common.codeenum.CodeEnum;
import com.ff.sca.common.codeenum.OperateModule;
import com.ff.sca.common.codeenum.OperateType;
import com.ff.sca.common.entity.resmsg.LayuiTableResMsg;
import com.ff.sca.common.entity.resmsg.ResMsg;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.DateUtil;
import com.ff.sca.product.entity.KvmGiftProduct;
import com.ff.sca.product.entity.KvmProduct;
import com.ff.sca.product.entity.KvmProductHot;
import com.ff.sca.product.entity.KvmProductRob;
import com.ff.sca.product.service.IKvmGiftProductService;
import com.ff.sca.product.service.IKvmProductHotService;
import com.ff.sca.product.service.IKvmProductRobService;
import com.ff.sca.product.service.IKvmProductService;
import com.ff.sca.system.entity.KvmSysCode;
import com.ff.sca.system.service.IKvmSysCodeService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品 前端控制器
 * </p>
 *
 * @author gw123
 * @since 2018-11-26
 */
@Controller
@RequestMapping("/kvmProduct")
public class KvmProductController extends BaseController {

    @Autowired
    private IKvmProductService productService;
    @Autowired
    private IKvmSysCodeService sysCodeService;
    @Autowired
    private IKvmProductHotService productHotService;
    @Autowired
    private IKvmProductRobService productRobService;
    @Autowired
    private IKvmGiftProductService giftProductService;


    /**
     * 获取签到奖品下拉
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSigninGifts", method = RequestMethod.POST)
    public ResMsg getSigninGifts() {
        try {
            return resSuccess(giftProductService.selectList(null));
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 获取礼包内容商品
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLibaoItems", method = RequestMethod.POST)
    public ResMsg getLibaoItems(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                if (product != null) {
                    if (CharUtil.isNotEmpty(product.getItems())) {
                        JSONArray json = JSONArray.fromObject(product.getItems());
                        List<KvmProduct> list = new ArrayList();
                        for (int i = 0; i < json.size(); i++) {
                            JSONObject item = json.getJSONObject(i);
                            KvmProduct pro = productService.selectById(Integer.parseInt(item.get("productId").toString()));
                            if (pro != null) {
                                pro.setParam(item.get("quantity").toString());
                                list.add(pro);
                            }
                        }
                        return resSuccess(list);
                    } else {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 获取礼包商品下拉
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLibaos", method = RequestMethod.POST)
    public ResMsg getLibaos() {
        try {
            return resSuccess(productService.selectList(new EntityWrapper<KvmProduct>().eq("type", 7)));
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 取消特色商品
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelFeaturesProduct", method = RequestMethod.POST)
    public ResMsg cancelFeaturesProduct(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                product.setType(0);
                Boolean result = productService.updateById(product);
                if (result) {
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 设置为特色商品
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setFeaturesProduct", method = RequestMethod.POST)
    public ResMsg setFeaturesProduct(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                product.setType(5);
                Boolean result = productService.updateById(product);
                if (result) {
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 加入到奖品区域
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "商品加入到奖品区",
            module = OperateModule.ProductManager,
            opType = OperateType.create
    )
    @ResponseBody
    @RequestMapping(value = "/product2GiftSpace", method = RequestMethod.POST)
    public ResMsg product2GiftSpacae(Integer productId, KvmGiftProduct per) {
        try {
            if (CharUtil.isNotEmpty(productId)) {
                KvmGiftProduct giftProduct = giftProductService.selectOne(new EntityWrapper<KvmGiftProduct>().eq("product_id", productId));
                if (giftProduct == null) {
                    KvmProduct product = productService.selectById(productId);
                    per.setName(product.getName());
                    per.setImg(product.getImg());
                    per.setIcon(product.getIcon());
                    per.setCreateTime(new Date());
                    per.setDetail(product.getDetail());
                    per.setPrice(0D);//奖品无价格
                    per.setProductId(product.getId());
                    per.setGetTimes(0);//默认领取次数0
                    per.setSort(0);
                    per.setDes(product.getRemark());
                    per.setDetail(product.getDetail());
                    per.setPostage(15D);
                    Boolean result = giftProductService.insert(per);
                    if (result) {
                        product.setType(ProductTypeEnum.SIGIN_GIFY.getType());
                        Boolean result2 = productService.updateById(product);
                        if (result2) {
                            return resSuccess(null);
                        }
                    }
                } else {
                    return resAreadyExisted(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 加入抢购区域
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "商品加入到抢购区",
            module = OperateModule.ProductManager,
            opType = OperateType.create
    )
    @ResponseBody
    @RequestMapping(value = "/product2RobSpace", method = RequestMethod.POST)
    public ResMsg product2RobSpace(KvmProductRob per, String startDate, String endDate) {
        try {
            if (CharUtil.isNotEmpty(per.getProductId())) {
                if (CharUtil.isNotEmpty(startDate)) {
                    per.setStartTime(DateUtil.stringToDate(startDate, "yyyy-MM-dd HH:mm:ss"));
                }
                if (CharUtil.isNotEmpty(endDate)) {
                    per.setEndTime(DateUtil.stringToDate(endDate, "yyyy-MM-dd HH:mm:ss"));
                }
                KvmProduct product = productService.selectById(per.getProductId());
                KvmProductRob productRob = productRobService.selectOne(new EntityWrapper<KvmProductRob>().eq("product_id", per.getProductId()));
                if (productRob == null) {
                    per.setProductNo(product.getProductNo());
                    per.setCreateTime(new Date());
                    Boolean result = productRobService.insert(per);
                    if (result) {
                        product.setRobPrice(per.getPriceRob());
                        product.setType(ProductTypeEnum.ROB.getType());
                        Boolean result2 = productService.updateById(product);
                        if (result2) {
                            return resSuccess(null);
                        }
                    }
                } else {
                    return new ResMsg(CodeEnum.HTTP_400.getCode(), "此商品已经被添加到抢购专区", null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 加入热销区域
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "商品加入到热销区",
            module = OperateModule.ProductManager,
            opType = OperateType.create
    )
    @ResponseBody
    @RequestMapping(value = "/product2HotSpace", method = RequestMethod.POST)
    public ResMsg product2HotSpace(KvmProductHot per) {
        try {
            if (CharUtil.isNotEmpty(per.getProductId())) {
                KvmProduct product = productService.selectById(per.getProductId());
                KvmProductHot productHot = productHotService.selectOne(new EntityWrapper<KvmProductHot>().eq("product_id", per.getProductId()));
                if (productHot == null) {
                    per.setProductNo(product.getProductNo());
                    per.setCreateTime(new Date());
                    Boolean result = productHotService.insert(per);
                    if (result) {
                        product.setHotPrice(per.getPriceHot());
                        product.setType(ProductTypeEnum.HOT.getType());
                        Boolean result2 = productService.updateById(product);
                        if (result2) {
                            return resSuccess(null);
                        }
                    }
                } else {
                    return new ResMsg(CodeEnum.HTTP_400.getCode(), "此商品已经被添加到热销专区", null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 商品设置首页显示取消
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "操作商品取消首页显示",
            module = OperateModule.ProductManager,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/productHomePageHide", method = RequestMethod.POST)
    public ResMsg productHomePageHide(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                product.setTop(0);
                Boolean result = productService.updateById(product);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 商品设置首页显示
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "操作商品设置为首页显示",
            module = OperateModule.ProductManager,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/productHomePageShow", method = RequestMethod.POST)
    public ResMsg productHomePageShow(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {

                KvmSysCode home_page_product_num = sysCodeService.selectOne(new EntityWrapper<KvmSysCode>().eq("name", "home_page_product_num"));
                if (home_page_product_num != null) {
                    int topCount = productService.selectCount(new EntityWrapper<KvmProduct>().eq("top", 1));
                    if (topCount < Integer.parseInt(home_page_product_num.getCode())) {
                        KvmProduct product = productService.selectById(id);
                        product.setTop(1);
                        Boolean result = productService.updateById(product);
                        if (result) {
                            return resSuccess(null);
                        }
                    } else {
                        return new ResMsg(CodeEnum.HTTP_400.getCode(), "商城首页设置显示商品数量已达到上限，如需继续添加，可在系统参数（home_page_product_num）设置！", null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 商品上架操作
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "商品上架",
            module = OperateModule.ProductManager,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/productPutaway", method = RequestMethod.POST)
    public ResMsg productPutaway(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                product.setStatus(1);
                Boolean result = productService.updateById(product);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 商品下架操作
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "商品下架",
            module = OperateModule.ProductManager,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/productSoldOut", method = RequestMethod.POST)
    public ResMsg productSoldOut(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmProduct product = productService.selectById(id);
                product.setStatus(0);
                Boolean result = productService.updateById(product);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/product", method = RequestMethod.POST)
    public ResMsg product(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                return resSuccess(productService.selectById(id));
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 通过商品编号查看商品详情
     *
     * @param No
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/productByNo", method = RequestMethod.POST)
    public ResMsg product(String No) {
        try {
            if (CharUtil.isNotEmpty(No)) {
                return resSuccess(productService.selectOne(new EntityWrapper<KvmProduct>().eq("product_no", No)));
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 新增商品
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "新增商品",
            module = OperateModule.ProductManager,
            opType = OperateType.create
    )
    @ResponseBody
    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public ResMsg addProduct(KvmProduct per, String[] images, String ids) {
        try {
            if (CharUtil.isNotEmpty(per)) {
                per.setImg(dlStr(images));
                if (CharUtil.isNotEmpty(ids)) {
                    String[] idsarr = ids.split(",");
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < idsarr.length; i++) {
                        String[] ido = idsarr[i].split("-");
                        if (ido.length == 2) {
                            KvmProduct product = productService.selectById(Integer.parseInt(ido[0]));
                            JSONObject object = new JSONObject();
                            object.put("name", product.getName());
                            object.put("productId", product.getId().toString());
                            object.put("quantity", ido[1]);
                            object.put("price", product.getPrice());
                            jsonArray.add(object);
                        } else {
                            return resfail(null);
                        }
                    }
                    per.setItems(jsonArray.toString());
                }
                per.setProductNo(productService.getMaxProductNo());
                per.setCreateTime(new Date());
                boolean result = productService.insert(per);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 商品修改
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "修改商品信息",
            module = OperateModule.ProductManager,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/updProduct", method = RequestMethod.POST)
    public ResMsg updProduct(KvmProduct per, String[] images, String ids) {
        try {
            if (CharUtil.isNotEmpty(per.getId())) {
                per.setImg(dlStr(images));
                if (CharUtil.isNotEmpty(ids)) {
                    String[] idsarr = ids.split(",");
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < idsarr.length; i++) {
                        String[] ido = idsarr[i].split("-");
                        if (ido.length == 2) {
                            KvmProduct product = productService.selectById(Integer.parseInt(ido[0]));
                            JSONObject object = new JSONObject();
                            object.put("name", product.getName());
                            object.put("productId", product.getId().toString());
                            object.put("quantity", ido[1]);
                            object.put("price", product.getPrice());
                            jsonArray.add(object);
                        } else {
                            return resfail(null);
                        }
                    }
                    per.setItems(jsonArray.toString());
                }
                KvmProduct product = per.selectById(per.getId());
                per.setCreateTime(product.getCreateTime());
                per.setProductNo(product.getProductNo());
                boolean result = productService.updateById(per);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    private String dlStr(String[] images) {
        if (images.length > 0) {
            String urlArr = "";
            for (int i = 0; i < images.length; i++) {
                urlArr += '"' + images[i] + '"';
                if (i < images.length - 1) {
                    urlArr += ",";
                }
            }
            urlArr = "[" + urlArr + "]";
            return urlArr;
        }
        return null;
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "删除商品",
            module = OperateModule.ProductManager,
            opType = OperateType.delete
    )
    @ResponseBody
    @RequestMapping(value = "/delProduct", method = RequestMethod.POST)
    public ResMsg delProduct(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                boolean result = productService.deleteById(id);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 商品列表
     *
     * @param page
     * @param size
     * @param per
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/productList", method = RequestMethod.POST)
    public LayuiTableResMsg noticeList(Integer page, Integer size, KvmProduct per) {
        try {
            Page<KvmProduct> pageEntity = setPageInfo(page, size);
            EntityWrapper<KvmProduct> ew = new EntityWrapper();
            if (CharUtil.isNotEmpty(per.getName())) {
                ew.like("name", per.getName());
            }
            if (CharUtil.isNotEmpty(per.getProductNo())) {
                ew.like("product_no", per.getProductNo());
            }
            if (CharUtil.isNotEmpty(per.getStatus())) {
                ew.eq("status", per.getStatus());
            }
            if (CharUtil.isNotEmpty(per.getCategory())) {
                ew.eq("category", per.getCategory());
            }
            if (CharUtil.isNotEmpty(per.getType())) {
                ew.eq("type", per.getType());
            }
            ew.orderBy("create_time", false);
            Page<KvmProduct> suserList = productService.selectPage(pageEntity, ew);
            long total = productService.selectCount(ew);
            return resTableSuccess(total, suserList.getRecords());

        } catch (Exception e) {
            e.printStackTrace();
            return resTableError(0, e.getMessage());
        }
    }
}

